
package com.qinbaokeji.checkpoint.dahuacamera.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qinbaokeji.checkpoint.dahuacamera.config.BeforeEndConfig;
import com.qinbaokeji.checkpoint.dahuacamera.config.CameraConfig;
import com.qinbaokeji.checkpoint.dahuacamera.config.DahuaServerConfig;
import com.qinbaokeji.checkpoint.dahuacamera.config.SystemConfig;
import com.qinbaokeji.checkpoint.dahuacamera.entity.CameraInfo;
import com.qinbaokeji.checkpoint.dahuacamera.service.ICameraInfoService;
import org.apache.commons.io.output.TeeOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.lang.management.ManagementFactory;

@Service
public class ListenerStarter implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ApplicationArguments applicationArguments;
    @Autowired
    private ICameraInfoService iCameraInfoService;
    @Autowired
    private DahuaServerConfig dahuaServerConfig;
    @Autowired
    private SystemConfig systemConfig;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent evt) {
        //1、获取路径
        String path;
        if(StringUtils.isEmpty(systemConfig.getPath())){
            path = applicationArguments.getNonOptionArgs().get(1);
        }else{
            path = systemConfig.getPath();
        }
        CameraConfig.setDllPath(path);
        //2、初始化监听程序
        String uuid = "";
        if(StringUtils.isEmpty(dahuaServerConfig.getStartUuid())){
            uuid = applicationArguments.getNonOptionArgs().get(0).replaceAll("\\\\","/");
        }else {
            uuid = dahuaServerConfig.getStartUuid();
        }
        LambdaQueryWrapper<CameraInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CameraInfo::getUuid,uuid);
        CameraInfo cameraInfo = iCameraInfoService.getOne(wrapper);
        //3、获取进程pid，并更新到数据库
        Integer pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
        cameraInfo.setPid(pid);
        iCameraInfoService.updateById(cameraInfo);
        //4、将控制台输出写入进日志文件
        File file = new File(path+"log/system-log/"+cameraInfo.logFileName());
        systemOutLog(file);
        start(cameraInfo);
        //5、开启程序结束处理线程
        new BeforeEndConfig(cameraInfo);
    }

    private void start(CameraInfo cameraInfo){
        Runnable runnable = () -> {
            try {
                new AlarmListener().start(cameraInfo);
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
        new Thread(runnable).start();
    }

    public static void systemOutLog(File file){
        try {
            FileOutputStream fos = new FileOutputStream(file);//f:生成的文件路径
            //we will want to print in standard "System.out" and in "file"
            TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
            PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
            System.setOut(ps);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
